from .common import *
import subprocess,pexpect
def before_request():
    pass
def checkserver():
    return successjson()
def outlogin():
    G.setadminlog="退出系统"
    account_token=request.args.get("account_token")
    if account_token:
        del_cache(account_token)
    else:
        del_session('userinfo')
    return successjson()
def get_account_token(username,sign,timestamp,random,types="get_account_token"):
    "获取用户token"
    G.setadminlog="获取用户token"
    status,code,msg,account_token=serlogin(username,sign,timestamp,random,types)
    if status:
        return successjson(data={"account_token":account_token},msg=msg)
    else:
        return errorjson(code=code,msg=msg)
def login(username,sign,timestamp,random,types="session"):
    "登录"
    G.setadminlog="登录系统"
    status,code,msg,account_token=serlogin(username,sign,timestamp,random,types)
    if status:
        return successjson(data=account_token,msg=msg)
    else:
        return errorjson(code=code,msg=msg)
def clistartplan():
    #这里是初始化计划任务 （cli方式运行）
    try:
        serverserverintervals=sqlite("interval",model_intapp_index_path).select()
        for serverserverinterval in serverserverintervals:
            if (times()-int(serverserverinterval['updtime'])) > 5:
                serverserverinterval['updtime']=times()
                sqlite("interval",model_intapp_index_path).where("id",serverserverinterval['id']).update(serverserverinterval)
                PLANTASK.plantask(serverserverinterval) #添加计划任务
    except:
        pass
def gitpull():
    "执行git"
    path=request.args.get('path')
    branch=request.args.get('branch') #强制更新指定分支
    title=request.args.get('title')
    if not title:
        title="执行命令 git pull 命令到"+path
    if 'Linux' in get_sysinfo()['platform']:
        shell='cd '+path+' && git reset --hard'
        if branch:
            shell+=' origin/'+branch
        shell+=' && git clean -f && git pull'
        Queues.insert(target=PUBLICOther.gitpull,args=(path,shell),title=title,describes="执行命令："+shell)
    elif 'Window' in get_sysinfo()['platform']:
        shell="git reset --hard"
        if branch:
            shell+=' origin/'+branch
        Queues.insert(target=PUBLICOther.gitpull,args=(path,shell),title=title,describes="执行命令："+shell)
        shell='git clean -f'
        Queues.insert(target=PUBLICOther.gitpull,args=(path,shell),title=title,describes="执行命令："+shell)
        shell='git pull'
        Queues.insert(target=PUBLICOther.gitpull,args=(path,shell),title=title,describes="执行命令："+shell)
    G.setadminlog="执行命令："+shell
    return successjson("命令已添加到任务队列中")
class PUBLICOther():
    def gitpull(path,shell):
        pi=subprocess.Popen(shell,shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        strs=pi.stdout.read().decode()
        # f=open(path+"/gitpull.log","w",encoding='utf-8')
        # f.write("\n时间:%s\n%s\n%s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),shell,strs))
        # f.close()


# def __createssl(data):
#     "创建Let's Encrypt免费证书"
#     # data=request.get_json()
#     if len(data['domain'])<1:
#         return errorjson(msg="至少添加一个域名")
#     path=os.path.split(os.path.realpath(__file__))[0]
#     # cmd='/intapp/letsencrypt/letsencrypt-auto certonly --standalone --email fk1402936534@qq.com -d test1.kwebapp.cn'
#     # cmd='/intapp/letsencrypt/letsencrypt-auto certonly --email fk1402936534@qq.com -d *.kwebapp.cn --manual --preferred-challenges dns --server https://acme-v02.api.letsencrypt.org/directory'
#     cmd=path+'/letsencrypt/letsencrypt-auto certonly --standalone --email '+data['email']
#     # cmd='/intapp/letsencrypt/letsencrypt-auto certonly --email '++data['email']
#     domain=''
#     for k in data['domain']:
#         if k['domain']:
#             cmd+=" -d "+k['domain']
#             domain+=k['domain']+"\n"
#         else:
#             return errorjson(msg="请输入域名")
#     # file_set_content("/etc/letsencrypt/live/"+str(data['domain'][0]['domain'])+"/config.conf",json_encode(conf))
#     if os.path.exists("/etc/letsencrypt/live/"+str(data['domain'][0]['domain'])):
#         shutil.rmtree("/etc/letsencrypt/live/"+str(data['domain'][0]['domain']))
#     if os.path.exists("/etc/letsencrypt/renewal/"+str(data['domain'][0]['domain'])):
#         shutil.rmtree("/etc/letsencrypt/renewal/"+str(data['domain'][0]['domain']))
#     # cmd+=' --manual --preferred-challenges dns --server https://acme-v02.api.letsencrypt.org/directory''
#     child = pexpect.spawn(cmd,timeout=180)
    
#     time.sleep(1)
#     index = child.expect(["gree","right IP address","No valid IP addresses","ongratulations","appropriate number","Problem binding to port 80","certificate and chain have been saved","ocsp.int-x3.letsencrypt.org", pexpect.EOF, pexpect.TIMEOUT])
#     print("index1",index)
#     if index == 0 :
#         child.sendline("A")
#         index = child.expect(["es", pexpect.EOF, pexpect.TIMEOUT])
#         print("index2",index)
#         if (index == 0):
#             child.sendline("Y")
#             index = child.expect(["(?i)ongratulations", pexpect.EOF, pexpect.TIMEOUT])
#             print("index3",index)
#             if index == 0:
#                 print("成功")
#                 conf={
#                     "data":data,
#                     "createtime":times(),
#                     "createdate":str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
#                 }
#                 file_set_content("/etc/letsencrypt/live/"+str(data['domain'][0]['domain'])+"/config.conf",json_encode(conf))
#                 child.close(force=True)
#                 raise Exception("Let's Encrypt申请成功,请到ssl证书夹查看")
#             else:
#                 print("error1")
#                 child.close(force=True)
#                 raise Exception("Let's Encrypt申请失败")
#         else:
#             raise Exception("申请失败,原因未知")
#             child.close(force=True)
#     elif index == 1 or index == 2:
#         child.close(force=True)
#         raise Exception("域名无法访问，你申请的域名可能没有解析到当前服务器或那您的域名没有备案")
#     elif index == 3:
#         conf={
#             "data":data,
#             "createtime":times(),
#             "createdate":str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
#         }
#         file_set_content("/etc/letsencrypt/live/"+str(data['domain'][0]['domain'])+"/config.conf",json_encode(conf))
#         child.close(force=True)
#         raise Exception("Let's Encrypt免费证书申请成功,请到ssl证书夹查看")
#     elif index == 4:
#         child.close(force=True)
#         raise Exception("该域名已签发，并在有效期内")
#     elif index == 5:
#         child.close(force=True)
#         raise Exception("80端口被占用,请停止占用80端口的程序后重新申请")
#     elif index == 6:
#         child.close(force=True)
#         conf={
#             "data":data,
#             "createtime":times(),
#             "createdate":str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
#         }
#         file_set_content("/etc/letsencrypt/live/"+str(data['domain'][0]['domain'])+"/config.conf",json_encode(conf))

#         raise Exception("Let's ssl申请成功,请到ssl证书夹查看")
#     elif index == 7:
#         child.close(force=True)
#         raise Exception("Let's ssl官网无法访问，请稍后或明日再试")
#     else:
#         print("error")
#         child.close(force=True)
#     raise Exception("Let's ssl申请失败")